<!-- 更新头像 -->
<template>
  <div>
    <img :src="img" alt="" ref="image" />

    <van-nav-bar
      left-text="返回"
      right-text="确认"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    />
  </div>
</template>

<script>
// 导入裁剪工具
import Cropper from "cropperjs";
import "cropperjs/dist/cropper.css";

import { updateUserPhoto } from "@/api/user.js";
import { Toast } from "vant";
export default {
  name: "UpdatePhoto",
  data() {
    return {
      img: window.URL.createObjectURL(this.ImgBlob),
      cropper: null, //裁剪框实例
    };
  },
  props: {
    ImgBlob: {
      required: true,
    },
  },
  methods: {
    getCroppedCanvas() {
      // 2.封装裁剪画面
      return new Promise((resolve) => {
        this.cropper.getCroppedCanvas().toBlob((file) => {
          resolve(file);
        });
      });
    },

    async onConfirm() {
      try {
        Toast.loading({
          forbidClick: true,
          message: "保存中..",
          duration: 0,
        });

        // 3.获取到选框内容
        const file = await this.getCroppedCanvas();
        const fd = new FormData(); //提交图片需要使用FormData表单格式
        fd.append("photo", file);
        await updateUserPhoto(fd);

        Toast.success("更新成功");
        this.$store.commit("removeCachePage", "LayoutIndex");
        this.$emit("updatePhoto", window.URL.createObjectURL(file));
        this.$emit("close");

      } catch (err) {
        console.dir(err);
        Toast.success("更新失败");
      }
    },
  },
  mounted() {
    const image = this.$refs.image;
    // 1.实例化裁剪器
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: "move",
      aspectRatio: 1,
      cropBoxMovable: false, //裁切框移动
      cropBoxResizable: false, //裁切框调整大小
      background: false,
      movable: true,
    });
  },
};
</script>

<style lang="less" scoped>
/deep/.van-nav-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #000;
  font-size: 18px;
}
img {
  display: block;

  /* This rule is very important, please don't ignore this */
  max-width: 100%;
}
</style>